import axios from 'axios';
import { ESort, IGetProductsResponse, IProductFilter, IReqCancel, IReqResult, IResult, productFilter, Result } from '../models';
import { _getProducts as mockGetProducts } from "./__mocks__/products";
const CancelToken = axios.CancelToken;

const isProduction = process.env.NODE_ENV === 'production';

function localFilterProducts(data: IGetProductsResponse, filter: IProductFilter, pageSize: number, pageNum: number): IGetProductsResponse {
  if (filter) {
    if (filter.sort && filter.sortProp) {
      //有排序
      if (filter.sort === ESort.Asc) {
        data.products.sort((a, b) => (a as any)[filter.sortProp!] - (b as any)[filter.sortProp!]);
      } else {
        data.products.sort((a, b) => (b as any)[filter.sortProp!] - (a as any)[filter.sortProp!]);
      }
    }
    data.products = data.products.filter(p => productFilter(p, filter));
  }
  data.products = data.products.slice(pageSize * (pageNum - 1), pageSize * pageNum);
  return data;
}
/**
 * 基础方法
 * @param isProduction 
 * @param filter 
 * @param pageSize 
 * @param pageNum 
 * @returns products 
 */
export function getProducts(filter: IProductFilter, pageSize: number, pageNum: number): IReqResult<IGetProductsResponse> {

  if (!isProduction) {
    //本地开发使用模拟数据,延时1s, 并随机出错
    return mockGetProducts(filter, pageSize, pageNum, 1000, true);
  }

  let task: Promise<IResult<IGetProductsResponse>>;
  let cancelToken: IReqCancel;
  const source = CancelToken.source();
  task = axios
    .get<IGetProductsResponse>(
      'https://react-shopping-cart-67954.firebaseio.com/products.json',
      {
        cancelToken: source.token
      }
    )
    .then(res => {
      //模拟筛选和分页
      const data = localFilterProducts(res.data, filter, pageSize, pageNum);
      return Result.success(data);
    })
    .catch(err => Result.error(err?.status ?? 500, err?.message ?? err));
  cancelToken = source;

  return {
    task,
    cancelToken,
  };
};
